/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.Person;
import entities.Subject;
import java.util.List;
import entities.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Оксана
 */
public class TestDaoImpl extends AbstractDao implements TestDao {
    
    @Autowired
    public TestDaoImpl(JdbcTemplate jdbcTemplate) {
        super(jdbcTemplate);
    }   

    @Override
    public void create(Test test) {
        jdbcTemplate.update("insert into tests (id, questions, variants, subject, "
                + "tutor) values (?, ?, ?, ?, ?)", test.getId(), test.getQuests(),
                test.getVariants(), test.getSubject().getId(), test.getTutor().getId());
    }

    @Override
    public Test findById(Integer id) {
        return jdbcTemplate.queryForObject("select id, questions, variants, subject, "
                + "tutor from tests where id = ?", new Object[] {id}, new TestMapper());
    }

    @Override
    public List<Test> findByTutorId(Integer tutorId) {
        return jdbcTemplate.query("select id, questions, variants, subject, tutor "
                + "from tests where tutor = ?", new Object[] {tutorId}, new TestMapper());
    }

    @Override
    public List<Test> findBySubjectId(Integer subjectId) {
        return jdbcTemplate.query("select id, questions, variants, subject, tutor "
                + "from tests where subject = ?", new Object[] {subjectId}, new TestMapper());
    }

    @Override
    public List<Test> findAll() {
        return jdbcTemplate.query("select id, questions, variants, subject, tutor "
                + "from tests", new TestMapper());
    }

    private final static class TestMapper implements RowMapper<Test> {

        @Override
        public Test mapRow(ResultSet rs, int i) throws SQLException {
            Test test = new Test();
            test.setId(rs.getInt("id"));
            test.setQuests(rs.getInt("questions"));
            test.setVariants(rs.getInt("variants"));
            Subject subject = new Subject();
            subject.setId(rs.getInt("subject"));
            test.setSubject(subject);
            Person tutor = new Person();
            tutor.setId(rs.getInt("tutor"));
            test.setTutor(tutor);
            return test;
        }
    }
}
